package flc.ast.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.app.Dialog;
import android.graphics.Color;
import android.media.MediaMetadataRetriever;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.SeekBar;
import android.widget.TextView;

import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.PathUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.stark.ve.EditorHolder;
import com.stark.ve.core.IEditorListener;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import flc.ast.BaseAc;
import flc.ast.HomeActivity;
import flc.ast.R;
import flc.ast.adapter.FormatAdapter;
import flc.ast.bean.FormatBean;
import flc.ast.databinding.ActivityPlayFormatBinding;
import flc.ast.utils.Content;
import io.reactivex.rxjava3.core.ObservableEmitter;
import stark.common.basic.media.video.VideoFormat;
import stark.common.basic.utils.FileP2pUtil;
import stark.common.basic.utils.FileUtil;
import stark.common.basic.utils.MediaUtil;
import stark.common.basic.utils.RxUtil;
import stark.common.basic.utils.StkPermissionHelper;
import stark.common.basic.utils.TimeUtil;
import stark.common.basic.view.container.StkRecycleView;

public class PlayFormatActivity extends BaseAc<ActivityPlayFormatBinding> {

    public static String videoPath;
    private Dialog myRenameDialog, myFblDialog, myMlDialog, myZlDialog, myFormatTurnDialog;
    private String selFormat = "", selFbl = "", selMl = "", selZl = "", newName = "";
    private EditText dialogRename;
    private FormatAdapter fblAdapter, mlAdapter, zlAdapter;
    private List<FormatBean> fblList = new ArrayList<>();
    private List<FormatBean> mlList = new ArrayList<>();
    private List<FormatBean> zlList = new ArrayList<>();
    private int oldPosition1 = 0, oldPosition2 = 0, oldPosition3;
    private ProgressBar pbFormat;
    private TextView dialogFormatTurnTitle, dialogFormatTurnText, dialogFormatPro, dialogFormatTurnComp;

    private long videoLength;
    private Handler mHandler;
    private final Runnable mTaskUpdateTime = new Runnable() {
        @Override
        public void run() {
            mDataBinding.tvVideoSbLeft.setText(TimeUtil.getMmss(mDataBinding.videoView.getCurrentPosition()));
            mDataBinding.sbVideo.setProgress(Integer.parseInt(TimeUtils.millis2String(mDataBinding.videoView.getCurrentPosition(), "ss")));
            mHandler.postDelayed(this, 500);
        }
    };

    @Override
    protected int onCreate() {
        return R.layout.activity_play_format;
    }

    @Override
    protected void initView() {
        mDataBinding.ivPlayFormatBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        mDataBinding.ivVideoPlay.setOnClickListener(this);
        mDataBinding.llPlayFormatBottom.setOnClickListener(null);
        mDataBinding.tvFormatMp4.setOnClickListener(this);
        mDataBinding.tvFormat3gp.setOnClickListener(this);
        mDataBinding.tvFormatAvi.setOnClickListener(this);
        mDataBinding.tvFormatMkv.setOnClickListener(this);
        mDataBinding.tvFormatMov.setOnClickListener(this);
        mDataBinding.llFileName.setOnClickListener(this);
        mDataBinding.llFbl.setOnClickListener(this);
        mDataBinding.llMl.setOnClickListener(this);
        mDataBinding.llZl.setOnClickListener(this);
        mDataBinding.tvPlayFormatStart.setOnClickListener(this);
        fblDialog();
        mlDialog();
        zlDialog();
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.ivVideoPlay://播放暂停
                if (mDataBinding.videoView.isPlaying()) {
                    mDataBinding.ivVideoPlay.setImageResource(R.drawable.bofang1);
                    mDataBinding.videoView.pause();
                    stopTime();
                } else {
                    mDataBinding.ivVideoPlay.setImageResource(R.drawable.zanting1);
                    mDataBinding.videoView.start();
                    startTime();
                }
                break;
            case R.id.tvFormatMp4:
                clearFormat();
                mDataBinding.tvFormatMp4.setBackgroundResource(R.drawable.kk2);
                selFormat = "mp4";
                break;
            case R.id.tvFormat3gp:
                clearFormat();
                mDataBinding.tvFormat3gp.setBackgroundResource(R.drawable.kk2);
                selFormat = "3gp";
                break;
            case R.id.tvFormatMkv:
                clearFormat();
                mDataBinding.tvFormatMkv.setBackgroundResource(R.drawable.kk2);
                selFormat = "mkv";
                break;
            case R.id.tvFormatMov:
                clearFormat();
                mDataBinding.tvFormatMov.setBackgroundResource(R.drawable.kk2);
                selFormat = "mov";
                break;
            case R.id.tvFormatAvi:
                clearFormat();
                mDataBinding.tvFormatAvi.setBackgroundResource(R.drawable.kk2);
                selFormat = "avi";
                break;
            case R.id.llFileName:
                renameDialog();
                myRenameDialog.show();
                break;
            case R.id.ivDialogFormatRenameCancel:
                myRenameDialog.dismiss();
                break;
            case R.id.ivDialogFormatRenameConfirm:
                newName = dialogRename.getText().toString();
                mDataBinding.tvFileName.setText(newName);
                myRenameDialog.dismiss();
                break;
            case R.id.llFbl:
                myFblDialog.show();
                break;
            case R.id.ivDialogFblConfirm:
                selFbl = fblAdapter.getItem(oldPosition1).getStr();
                mDataBinding.tvFbl.setText(selFbl);
                myFblDialog.dismiss();
                break;
            case R.id.ivDialogFblCancel:
                myFblDialog.dismiss();
                break;
            case R.id.llMl:
                myMlDialog.show();
                break;
            case R.id.ivDialogMlConfirm:
                selMl = mlAdapter.getItem(oldPosition2).getStr();
                mDataBinding.tvMl.setText(selMl);
                myMlDialog.dismiss();
                break;
            case R.id.ivDialogMlCancel:
                myMlDialog.dismiss();
                break;
            case R.id.llZl:
                myZlDialog.show();
                break;
            case R.id.ivDialogZlConfirm:
                selZl = zlAdapter.getItem(oldPosition3).getStr();
                mDataBinding.tvZl.setText(selZl);
                myZlDialog.dismiss();
                break;
            case R.id.ivDialogZlCancel:
                myZlDialog.dismiss();
                break;
            case R.id.tvPlayFormatStart:
                formatTurnDialog();
                startConv();
                break;
            case R.id.tvDialogFormatTurnComp:
                myFormatTurnDialog.dismiss();
                startActivity(HomeActivity.class);
                finish();
                break;

        }
    }

    @Override
    protected void onItemClickCallback(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        if (adapter == fblAdapter) {
            fblAdapter.getItem(oldPosition1).setSelect(false);
            fblAdapter.notifyItemChanged(oldPosition1);
            oldPosition1 = position;
            fblAdapter.getItem(position).setSelect(true);
            fblAdapter.notifyItemChanged(position);
        } else if (adapter == mlAdapter) {
            mlAdapter.getItem(oldPosition2).setSelect(false);
            mlAdapter.notifyItemChanged(oldPosition2);
            oldPosition2 = position;
            mlAdapter.getItem(position).setSelect(true);
            mlAdapter.notifyItemChanged(position);
        } else if (adapter == zlAdapter) {
            zlAdapter.getItem(oldPosition3).setSelect(false);
            zlAdapter.notifyItemChanged(oldPosition3);
            oldPosition3 = position;
            zlAdapter.getItem(position).setSelect(true);
            zlAdapter.notifyItemChanged(position);
        }
    }

    @Override
    protected void initData() {
        //获取视频路径 时长
        if (TextUtils.isEmpty(videoPath)) return;
//        getVideoData();
        videoLength = MediaUtil.getDuration(videoPath);
        String fileName = FileUtils.getFileName(videoPath);
        int index = fileName.indexOf(".");
        String startFormat = fileName.substring(index + 1, fileName.length());
        mDataBinding.tvFileName.setText(getString(R.string.please_input_name));
        mDataBinding.tvZl.setText(getString(R.string.please_sel_zl));
        mDataBinding.tvFbl.setText(getString(R.string.please_sel_fbl));
        mDataBinding.tvMl.setText(getString(R.string.please_sel_ml));
        mDataBinding.tvStartFormat.setText(getString(R.string.play_format_text2) + startFormat);
    }

    //设置播放器
    private void setPlayer() {
        mHandler = new Handler();
        //设置seekbar
        mDataBinding.sbVideo.setMax(Integer.parseInt(TimeUtils.millis2String(videoLength, "ss")));
        mDataBinding.tvVideoSbLeft.setText("00:00");
        mDataBinding.tvVideoSbRight.setText(TimeUtil.getMmss(videoLength));
        mDataBinding.sbVideo.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int i, boolean b) {

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                mDataBinding.videoView.seekTo(seekBar.getProgress());
            }
        });
        //设置播放器
        mDataBinding.videoView.setVideoPath(videoPath);
        mDataBinding.videoView.seekTo(1);
        mDataBinding.videoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {  // 播放完成的监听
                mDataBinding.tvVideoSbLeft.setText("00:00");
                mDataBinding.sbVideo.setProgress(0);
                mDataBinding.ivVideoPlay.setImageResource(R.drawable.bofang1);
                mp.seekTo(1);
                stopTime();
            }
        });
    }

    private void startTime() {
        mHandler.post(mTaskUpdateTime);
    }

    private void stopTime() {
        mHandler.removeCallbacks(mTaskUpdateTime);
    }

    @Override
    protected void onResume() {
        super.onResume();
        //设置播放器
        setPlayer();
        //直接播放视频
        mDataBinding.videoView.seekTo(1);
        mDataBinding.ivVideoPlay.setImageResource(R.drawable.zanting1);
        mDataBinding.videoView.start();
        startTime();
    }

    @Override
    protected void onStop() {
        super.onStop();
        stopTime();
    }

    //开始转换(帧率无效，不管它)
    private void comVideo(int videoWidth, int videoHeight, int ml, String format) {
        myFormatTurnDialog.show();

        EditorHolder.editor().videoCompress(videoPath, videoWidth, videoHeight, ml, new IEditorListener() {
            @Override
            public void onSuccess(String outFilePath) {
//                Log.e("TAG", "onProgress: " +22222);
                mDataBinding.tvPlayFormatStart.setEnabled(true);
                saveVideo(outFilePath, format);
            }

            @Override
            public void onFailure(String errMsg) {
                myFormatTurnDialog.dismiss();
                mDataBinding.tvPlayFormatStart.setEnabled(true);
                ToastUtils.showShort(R.string.conv_def);
            }

            @Override
            public void onProgress(int progress) {
                pbFormat.setProgress(progress);
                dialogFormatPro.setText(progress + getString(R.string.unit_percent));
                if (progress == 100) {
                    dialogFormatTurnComp.setVisibility(View.VISIBLE);
                    dialogFormatTurnTitle.setText(getString(R.string.format_comp_title));
                    dialogFormatTurnText.setText(getString(R.string.format_comp_tip));
                }
            }
        });
    }

    //保存视频
    private void saveVideo(String path, String format) {
        RxUtil.create(new RxUtil.Callback<String>() {
            @Override
            public void doBackground(ObservableEmitter<String> emitter) {
                String filePath = FileUtil.generateFilePath(Content.myTemp, format);
                FileUtils.copy(path, filePath);
                emitter.onNext(filePath);
            }

            @Override
            public void accept(String savePath) {
                //重命名
                FileUtils.rename(savePath, newName + format);
                String newPath = PathUtils.getFilesPathExternalFirst() + Content.myTemp + "/" + newName + format;
                //保存到相册
                FileP2pUtil.copyPrivateVideoToPublic(mContext, newPath);
                mDataBinding.tvPlayFormatStart.setEnabled(true);
            }
        });
    }

    //开始转换
    private void startConv() {
        if (TextUtils.isEmpty(selFormat)) {
            ToastUtils.showShort(R.string.please_sel_format);
        } else if (TextUtils.isEmpty(newName)) {
            ToastUtils.showShort(R.string.please_input_name);
        } else if (TextUtils.isEmpty(selFbl)) {
            ToastUtils.showShort(R.string.please_sel_fbl);
        } else if (TextUtils.isEmpty(selMl)) {
            ToastUtils.showShort(R.string.please_sel_ml);
        } else if (TextUtils.isEmpty(selZl)) {
            ToastUtils.showShort(R.string.please_sel_zl);
        } else {
            mDataBinding.tvPlayFormatStart.setEnabled(false);
            //整理参数
            int width = getWidth();
            int height = getHeight();
            int ml1 = getMl();
            String format = getFormat();
            comVideo(width, height, ml1, format);//修改参数其实就是压缩视频
        }
    }

    //根据选择的分辨率获取宽
    private int getWidth() {
        int width = 0;
        if (selFbl.equals("2k")) {
            width = 2560;
        } else if (selFbl.equals("1080P")) {
            width = 1920;
        } else if (selFbl.equals("720P")) {
            width = 1280;
        } else if (selFbl.equals("540P")) {
            width = 960;
        } else if (selFbl.equals("480P")) {
            width = 640;
        }
        return width;
    }

    //根据选择的分辨率获取高
    private int getHeight() {
        int height = 0;
        if (selFbl.equals("2k")) {
            height = 1440;
        } else if (selFbl.equals("1080P")) {
            height = 1080;
        } else if (selFbl.equals("720P")) {
            height = 720;
        } else if (selFbl.equals("540P")) {
            height = 540;
        } else if (selFbl.equals("480P")) {
            height = 480;
        }
        return height;
    }

    //根据选择的码率获取码率比例
    private int getMl() {
        int mBitrateScale = 0;
        if (selMl.equals("250kps")) {
            mBitrateScale = 250 * 1024;
        } else if (selMl.equals("2000kbps")) {
            mBitrateScale = 2000 * 1024;
        } else if (selMl.equals("5000kbps")) {
            mBitrateScale = 5000 * 1024;
        } else if (selMl.equals("8000kbps")) {
            mBitrateScale = 8000 * 1024;
        }
        return mBitrateScale;
    }

    //根据选择的格式获取格式后缀
    private String getFormat() {
        String format = VideoFormat.MP4.getSuffix();
        if (selFormat.equals("mp4")) {
            format = VideoFormat.MP4.getSuffix();
        } else if (selFormat.equals("avi")) {
            format = VideoFormat.AVI.getSuffix();
        } else if (selFormat.equals("mkv")) {
            format = VideoFormat.MKV.getSuffix();
        } else if (selFormat.equals("3gp")) {
            format = VideoFormat.THREE_GP.getSuffix();
        } else if (selFormat.equals("mov")) {
            format = VideoFormat.MOV.getSuffix();
        }
        return format;
    }

    private void renameDialog() {
        myRenameDialog = new Dialog(mContext, R.style.DialogStyle);
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_format_rename, null);
        myRenameDialog.setContentView(inflate);
        myRenameDialog.setCancelable(true);
        Window dialogWindow = myRenameDialog.getWindow();
        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.BOTTOM);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (dm.widthPixels * 0.9);
        lp.y = 50;
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);
        ImageView cancel = inflate.findViewById(R.id.ivDialogFormatRenameCancel);
        ImageView comp = inflate.findViewById(R.id.ivDialogFormatRenameConfirm);
        TextView dialogFormat = inflate.findViewById(R.id.tvDialogFormat);
        dialogRename = inflate.findViewById(R.id.etDialogFormatRename);
        String fileName = FileUtils.getFileName(videoPath);
        int index = fileName.indexOf(".");
        String startFormat = fileName.substring(index + 1, fileName.length());
        dialogFormat.setText("." + startFormat);
        if (selFormat.isEmpty()){
            dialogFormat.setText("." + startFormat);
        }else {
            dialogFormat.setText("." + selFormat);
        }
//        newName=dialogRename.getText().toString()+"."+startFormat;
        cancel.setOnClickListener(this);
        comp.setOnClickListener(this);
    }

    private void fblDialog() {
        myFblDialog = new Dialog(mContext, R.style.DialogStyle);
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_fbl, null);
        myFblDialog.setContentView(inflate);
        myFblDialog.setCancelable(true);
        Window dialogWindow = myFblDialog.getWindow();
        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.BOTTOM);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (dm.widthPixels * 0.9);
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);

        ImageView dialogComp = inflate.findViewById(R.id.ivDialogFblConfirm);
        ImageView dialogCancel = inflate.findViewById(R.id.ivDialogFblCancel);
        dialogComp.setOnClickListener(this);
        dialogCancel.setOnClickListener(this);

        StkRecycleView recycleView = inflate.findViewById(R.id.rvDialogFormatList);
        recycleView.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false));
        fblAdapter = new FormatAdapter();
        recycleView.setAdapter(fblAdapter);
        fblList.add(new FormatBean("2k", true));
        fblList.add(new FormatBean("1080P", false));
        fblList.add(new FormatBean("720P", false));
        fblList.add(new FormatBean("540P", false));
        fblList.add(new FormatBean("480P", false));
        fblAdapter.setList(fblList);
        fblAdapter.setOnItemClickListener(this);

    }

    private void mlDialog() {
        myMlDialog = new Dialog(mContext, R.style.DialogStyle);
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_ml, null);
        myMlDialog.setContentView(inflate);
        myMlDialog.setCancelable(true);
        Window dialogWindow = myMlDialog.getWindow();
        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.BOTTOM);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (dm.widthPixels * 0.9);
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);

        ImageView dialogComp = inflate.findViewById(R.id.ivDialogMlConfirm);
        ImageView dialogCancel = inflate.findViewById(R.id.ivDialogMlCancel);
        dialogComp.setOnClickListener(this);
        dialogCancel.setOnClickListener(this);

        StkRecycleView recycleView = inflate.findViewById(R.id.rvDialogFormatList);
        recycleView.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false));
        mlAdapter = new FormatAdapter();
        recycleView.setAdapter(mlAdapter);
        mlList.add(new FormatBean("250kbps", true));
        mlList.add(new FormatBean("2000kbps", false));
        mlList.add(new FormatBean("5000kbps", false));
        mlList.add(new FormatBean("8000kbps", false));
        mlAdapter.setList(mlList);
        mlAdapter.setOnItemClickListener(this);

    }

    private void zlDialog() {
        myZlDialog = new Dialog(mContext, R.style.DialogStyle);
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_zl, null);
        myZlDialog.setContentView(inflate);
        myZlDialog.setCancelable(true);
        Window dialogWindow = myZlDialog.getWindow();
        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.BOTTOM);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (dm.widthPixels * 0.9);
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);

        ImageView dialogComp = inflate.findViewById(R.id.ivDialogZlConfirm);
        ImageView dialogCancel = inflate.findViewById(R.id.ivDialogZlCancel);
        dialogComp.setOnClickListener(this);
        dialogCancel.setOnClickListener(this);

        StkRecycleView recycleView = inflate.findViewById(R.id.rvDialogFormatList);
        recycleView.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false));
        zlAdapter = new FormatAdapter();
        recycleView.setAdapter(zlAdapter);
        zlList.add(new FormatBean("80fps", true));
        zlList.add(new FormatBean("50fps", false));
        zlList.add(new FormatBean("40fps", false));
        zlList.add(new FormatBean("30fps", false));
        zlList.add(new FormatBean("20fps", false));
        zlAdapter.setList(zlList);
        zlAdapter.setOnItemClickListener(this);

    }

    private void formatTurnDialog() {
        myFormatTurnDialog = new Dialog(mContext, R.style.DialogStyle);
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_format_turn, null);
        myFormatTurnDialog.setContentView(inflate);
        myFormatTurnDialog.setCancelable(false);
        Window dialogWindow = myFormatTurnDialog.getWindow();
        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.BOTTOM);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (dm.widthPixels * 0.9);
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);

        dialogFormatTurnTitle = inflate.findViewById(R.id.tvDialogFormatTurnTitle);
        dialogFormatTurnText = inflate.findViewById(R.id.tvDialogFormatTurnText);
        dialogFormatPro = inflate.findViewById(R.id.tvDialogFormatPro);
        dialogFormatTurnComp = inflate.findViewById(R.id.tvDialogFormatTurnComp);
        pbFormat = inflate.findViewById(R.id.pbFormat);
        dialogFormatTurnComp.setOnClickListener(this);

    }

    private void clearFormat() {
        mDataBinding.tvFormatMov.setBackgroundResource(R.drawable.shape_format);
        mDataBinding.tvFormatMp4.setBackgroundResource(R.drawable.shape_format);
        mDataBinding.tvFormatMkv.setBackgroundResource(R.drawable.shape_format);
        mDataBinding.tvFormatAvi.setBackgroundResource(R.drawable.shape_format);
        mDataBinding.tvFormat3gp.setBackgroundResource(R.drawable.shape_format);
    }

}